﻿using Abp.Application.Services;
using Abp.Collections.Extensions;
using Abp.Domain.Repositories;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using SportsPlatform.Base;
using SportsPlatform.Consts;
using SportsPlatform.Dto.SportBusiness.ProjectType;
using SportsPlatform.Enums;
using SportsPlatform.Global;
using SportsPlatform.Helpers;
using SportsPlatform.Model.PermissionManagement;
using SportsPlatform.Model.SportBusiness;
using SportsPlatform.Query.SportBusiness.Project;
using SportsPlatform.SportBusiness.ISportBusiness;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SportsPlatform.SportBusiness.SportBusiness
{
    /// <summary>
    /// 项目管理服务实现
    /// </summary>
    [RemoteService(false)]
    public class ProjectService : SportsPlatformAppServiceBase, IProjectService
    {
        private readonly IRepository<Project, Guid> _repository;
        private readonly IRepository<UserInfo, Guid> _userreopsitory;
        private readonly IRepository<ProjectType, Guid> _typerepository;
        public ProjectService(IRepository<Project, Guid> repository, IRepository<UserInfo, Guid> userreopsitory,
            IRepository<ProjectType, Guid> typerepository, IHttpContextAccessor context) : base(context)
        {
            _repository = repository;
            _typerepository = typerepository;
            _userreopsitory = userreopsitory;
        }

        /// <summary>
        /// 添加项目信息
        /// </summary>
        /// <param name="addProjectInfo">项目信息参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> AddProject(AddProjectInfoQuery addProjectInfo)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var res = ObjectMapper.Map<Project>(addProjectInfo);

                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                res.Name = addProjectInfo.ProjectName;
                res.CreateTime = DateTime.Now;
                res.CreateUserId = token.Id;
                if (!addProjectInfo.TypeId.IsNullAndEmpty())
                {
                    var Parent = await _typerepository.SingleAsync(p => p.Id == addProjectInfo.TypeId);
                    if (Parent.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.IsSuccess = false;
                        resultDto.Message = "该分类不存在";
                        return resultDto;
                    }
                    res.ProjectTypeID = Parent.Id;
                }

                var category = await _repository.InsertAsync(res);

                resultDto.Code = !category.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !category.IsNullAndEmpty();
                resultDto.Message = !category.IsNullAndEmpty() ? "添加成功" : "添加失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 获取分页后项目列表
        /// </summary>
        /// <param name="query">查询参数</param>
        /// <returns></returns>
        public async Task<PagePagingDto<ProjectDto>> GetProject(GetProjectQuery query)
        {
            PagePagingDto<ProjectDto> result = new PagePagingDto<ProjectDto>();
            try
            {
                if (query.State.IsNullAndEmpty())
                {
                    query.State = -1;
                }
                var asyncres = await _repository.GetAllListAsync();
                List<ProjectDto> dtos = new List<ProjectDto>();
                var res = asyncres.WhereIf(!query.Keywords.IsNullAndEmpty(), c => c.Name.Contains(query.Keywords))
                    .WhereIf(query.State != -1, c => c.State == query.State)
                      .OrderByDescending(c => c.CreateTime)
                      .Select(p => new ProjectDto
                      {
                          CreateTime = p.CreateTime,
                          Id = p.Id,
                          Name = p.Name,
                          State = p.State,
                          ProjectTypeId = p.ProjectTypeID
                      });

                if (res.Count() > 0)
                {
                    foreach (var item in res.Skip((query.PageIndex - 1) * query.PageSize).Take(query.PageSize))
                    {
                        if (!item.ProjectTypeId.ToString().IsGuidByParse())
                        {
                            dtos.Add(new ProjectDto
                            {
                                State = item.State,
                                CreateTime = item.CreateTime,
                                Id = item.Id,
                                Name = item.Name,
                            });
                            break;
                        }
                        var type = await _typerepository.GetAsync(item.ProjectTypeId);

                        dtos.Add(new ProjectDto
                        {
                            State = item.State,
                            CreateTime = item.CreateTime,
                            Id = item.Id,
                            Name = item.Name,
                            ProjectTypeName = type.Name,
                            ProjectTypeId = item.ProjectTypeId
                        });
                    }

                    result.TotalCount = res.Count();
                    result.Code = HttpResultCode.Success;
                    result.IsSuccess = true;
                    result.Message = "查询成功";
                    result.Data = dtos;
                }
                else
                {
                    result.Code = HttpResultCode.Fail;
                    result.IsSuccess = false;
                    result.Message = "未查询到数据";
                }
            }
            catch (Exception e)
            {
                result.Code = HttpResultCode.Error;
                result.IsSuccess = false;
                result.Message = e.Message.ToString();
            }
            return result;
        }

        /// <summary>
        /// 客户端分页获取项目信息（用于信息同步）
        /// </summary>
        /// <param name="query"></param>
        /// <returns></returns>
        public async Task<PagePagingDto<GetPageProjectKHDDto>> GetPageProjectKHD(BasePageQuery query)
        {
            PagePagingDto<GetPageProjectKHDDto> pagingDto = new();
            try
            {
                var retlist = await _repository.GetAllListAsync(info => info.IsDeleted == false);
                var pageretlist = retlist.Skip(query.PageSize * (query.PageIndex - 1))
                .Take(query.PageSize).ToList();
                if (pageretlist != null && pageretlist.Count() > 0)
                {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.Success;
                    pagingDto.Message = "查询成功！";
                    pagingDto.Data = ObjectMapper.Map<List<GetPageProjectKHDDto>>(pageretlist);
                    pagingDto.TotalCount = retlist.Count;
                }
                else
                {
                    pagingDto.IsSuccess = true;
                    pagingDto.Code = HttpResultCode.NotData;
                    pagingDto.Message = "未查询到数据！";
                }
            }
            catch (Exception ex)
            {
                pagingDto.IsSuccess = false;
                pagingDto.Code = HttpResultCode.Error;
                pagingDto.Message = ex.Message.ToString();
            }
            return pagingDto;
        }

        /// <summary>
        /// 更新项目信息
        /// </summary>
        /// <param name="updateProjectInfo">更新参数</param>
        public async Task<BaseResultDto> UpdateInfo(UpdateProjectInfoQuery updateProjectInfo)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var res = ObjectMapper.Map<Project>(updateProjectInfo);
                var project = await _repository.GetAsync(res.Id);
                if (project.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前项目不存在";
                    return resultDto;
                }
                var token = UldAdminSessionContext.GetCurrentUserInfo(_context);

                project.Name = updateProjectInfo.ProjectName;
                project.UpdateTime = DateTime.Now;
                project.UpdateUserId = token.Id;
                project.State = updateProjectInfo.State;
                if (!updateProjectInfo.TypeId.IsNullAndEmpty())
                {
                    var Parent = await _typerepository.SingleAsync(p => p.Id == updateProjectInfo.TypeId);
                    if (Parent.IsNullAndEmpty())
                    {
                        resultDto.Code = HttpResultCode.Fail;
                        resultDto.IsSuccess = false;
                        resultDto.Message = "该分类不存在";
                        return resultDto;
                    }
                    project.ProjectTypeID = Parent.Id;
                }

                var category = await _repository.UpdateAsync(project);

                resultDto.Code = !category.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !category.IsNullAndEmpty();
                resultDto.Message = !category.IsNullAndEmpty() ? "更新成功" : "更新失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 更新项目状态
        /// </summary>
        /// <param name="updateProjectState">更新参数</param>
        /// <returns></returns>
        public async Task<BaseResultDto> UpdateState(UpdateProjectStateQuery updateProjectState)
        {
            BaseResultDto resultDto = new BaseResultDto();
            try
            {
                var res = ObjectMapper.Map<Project>(updateProjectState);
                var project = await _repository.GetAsync(res.Id);
                if (project.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前项目不存在";
                    return resultDto;
                }
                var user = await _userreopsitory.GetAsync(updateProjectState.UpdateUserId);
                if (user.IsNullAndEmpty())
                {
                    resultDto.Code = HttpResultCode.Fail;
                    resultDto.IsSuccess = false;
                    resultDto.Message = "当前用户不存在";
                    return resultDto;
                }
                project.UpdateTime = DateTime.Now;
                project.UpdateUserId = user.Id;
                project.State = updateProjectState.State;

                var category = await _repository.UpdateAsync(project);

                resultDto.Code = !category.IsNullAndEmpty() ? HttpResultCode.Success : HttpResultCode.SqlError;
                resultDto.IsSuccess = !category.IsNullAndEmpty();
                resultDto.Message = !category.IsNullAndEmpty() ? "更新状态成功" : "更新状态失败";
            }
            catch (Exception e)
            {
                resultDto.Code = HttpResultCode.Error;
                resultDto.IsSuccess = false;
                resultDto.Message = e.Message;
            }
            return resultDto;
        }

        /// <summary>
        /// 编辑比赛项目时选择项目类别列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetProjectTypeListDto>> GetProjectTypeList()
        {
            var res = new ResultListDto<GetProjectTypeListDto>();
            var list = new List<GetProjectTypeListDto>();
            //获取未删除的切没有禁用的项目类别
            var type = await _typerepository.GetAllListAsync(p => p.IsDeleted == false && p.State == true);
            if (type.Count > 0)
            {
                foreach (var item in type)
                {
                    list.Add(new GetProjectTypeListDto()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }

                res.Code = HttpResultCode.Success;
                res.IsSuccess = true;
                res.Message = "查询成功！";
                res.Data = list;
            }
            else
            {
                res.Code = HttpResultCode.NotData;
                res.IsSuccess = false;
                res.Message = "未查询到数据";
            }

            return res;
        }


        /// <summary>
        /// 编辑比赛项目时选择项目列表
        /// </summary>
        /// <returns></returns>
        public async Task<ResultListDto<GetProjectInfoDto>> GetProjectInfo(GetProjectInfoQuery query)
        {
            var res = new ResultListDto<GetProjectInfoDto>();
            var list = new List<GetProjectInfoDto>();
            var project = new List<Project>();
            if (query.Id == Guid.Empty || query.Id == null)
            {
                project = await _repository.GetAllListAsync(p => p.State == (int)EnableAndDisableStateEnum.启用);
            }
            else
            {
                project = await _repository.GetAllListAsync(p => p.ProjectTypeID == query.Id && p.State == (int)EnableAndDisableStateEnum.启用);
            }
            if (project.Count > 0)
            {
                foreach (var item in project)
                {
                    list.Add(new GetProjectInfoDto()
                    {
                        Id = item.Id,
                        Name = item.Name
                    });
                }

                res.Code = HttpResultCode.Success;
                res.IsSuccess = true;
                res.Message = "查询成功！";
                res.Data = list;
            }
            else
            {
                res.Code = HttpResultCode.NotData;
                res.IsSuccess = false;
                res.Message = "未查询到数据";
            }

            return res;
        }
    }
}
